﻿// baseUrl

function update ()
{
    var index = 0;

    // set custom fields names to match what mvc.net expects
    $('.Property', $("#CustomFields")).each(function ()
    {
        if ($('[for_saving="true"]', this).length)
        {
            $('[for_saving="true"]', this).each(function ()
            {
                $(this).attr('name', $(this).attr('name').replace(/\d+/, index));
            });
            index++;
        }
    });

    var data = $('form [for_saving="true"], form [always_save="true"]').serialize();
    $('.CreateForm').show_loading(true);

    for(var i=0; i<TaskDisplay.resources.added.length; i++)
        data += stringFormat("&added[{0}]={1}", i, TaskDisplay.resources.added[i].id);
    for(var i=0; i<TaskDisplay.resources.deleted.length; i++)
        data += stringFormat("&deleted[{0}]={1}", i, TaskDisplay.resources.deleted[i].rid);


    remoteRequest({
        url: baseUrl + "/tasks/edit",
        contentType: "JSON",
        type: "POST",
        data: data,
        success: function (res)
        {
            var form = $('.Info_Container');
            form.find('input, select, textarea').attr("for_saving", "false");

            resetCustomFields();
            $('.CreateForm').show_loading(false);
            if (res && res.Data)
            {
                TaskDisplay.resources.added = [];
                TaskDisplay.resources.deleted = [];
                var d = res.Data;

                //alert("The record has been updated.")
                var task = $('.Info_Container').data('task');
                $.extend(true, task, d.task);

                $('.highlight').removeClass('highlight');

                TaskDisplay.displayDetails(d.task, false);

                if (!d.I_StartDate)
                    $('[name=StartDate]').closest(".Property").find(".FormDisplay").addClass("highlight");
                if (!d.I_DueDate)
                    $('[name=DueDate]').closest(".Property").find(".FormDisplay").addClass("highlight");
                if (!d.I_Duration)
                {
                    $('[name=Duration.Value]').closest(".Property").find(".FormDisplay").addClass("highlight");
                    //$('[name=Duration.Unit]').addClass("highlight");
                }
            }
            else alert(res.ErrorMessage)
        }
    });
};

   

jQuery.inObjectArray = function(arr, func)
{
    for(var i=0;i<arr.length;i++)
        if(func(arr[i]))
            return i;
    return -1;
}

TaskDisplay =
{
    back: function ()
    {
        $('[name="ID.Value"]').val('');

        var task = $('.Info_Container').data('task');
        task.Loaded = true;
        $('#tasksContainer').clarizen_table('getSelectedElement', task);

        $('.Info_Container').data('task', null);
        $('#tasksDetails').fadeOut(300, function () { $('#tasksPage').fadeIn() });
    },
    cancel: function ()
    {
        var task = $('.Info_Container').data('task');
        $('.highlight').removeClass('highlight');
        TaskDisplay.displayDetails(task, false);
    },
    init: function ()
    {
        this.loadControls();

        var cols = [
            new Column({
                name: "",
                displayName: "",
                getData: function (item)
                {
                    return stringFormat("<img src='{0}/Images/{1}'/>", baseUrl, getStatusImage(item));
                },
                padding: 0,
                sortName: "TrackStatus"
            }),
            new Column({
                name: "",
                getData: function (item)
                {
                    return getImportanceImage(item)
                },
                sortName: "Importance",
                padding: 0
            })];

        if (!isWide)
            cols.push(new Column({
                name: "Name"
            }));
        else
        {
            cols.push(new Column({
                name: "Name"
            }));
            cols.push(new Column({
                name: "ParentProject_Name",
                displayName: "Project Name",
                sortName: "ParentProject"
            }));
            cols.push(new Column({
                name: "DueDateString",
                displayName: "Due Date",
                sortName: "DueDate"
            }));
            cols.push(new Column({
                name: "PercentCompleted",
                displayName: "% Completed",
                getData: function (item)
                {
                    return item.PercentCompleted ? Math.round(item.PercentCompleted) + "%" : "";
                }
            }));
        }

        var table = this;
        $('#tasksContainer').clarizen_table({
            cols: cols,
            page: function (page, callback)
            {
                table.load(page, function (data)
                {
                    $('#tasksContainer').clarizen_table('enablePaging', data.hasMore);
                    callback(data.list)
                });
            },
            headerClick: function ()
            {
                var col = $('#tasksContainer').clarizen_table("getCol", $(this));
                var state = col.options.sortName || col.options.name;

                if (do_sort.state == state)
                    do_sort.asc = !do_sort.asc;
                else
                {
                    do_sort.state = state;
                    do_sort.asc = true;
                }
                $('.sort').remove();
                $(this).append(stringFormat("<span class='sort {0}'>", do_sort.asc ? "down" : "up"));
                $('#tasksContainer th').removeClass('sorted');
                $(this).addClass('sorted');
                TaskDisplay.load(0, TaskDisplay.loadCallback);
            },
            baseUrl: baseUrl,
            spanHeaderText: true,
            height: $.browser.msie || $.browser.chrome ? 295 : 345,
            padding: 25,
            elements: [],
            alternateRowClass: "",
            afterCellClick: function ()
            {
                table.displayDetails(null, false);
            }
            //            ,afterCreated: function(rows)
            //            {
            //                rows.each(function()
            //                {
            //                    var task = $(this).data('entity');
            //                    $(this).find('td').each(function()
            //                    {
            //                        $(this).tipTip({content: $.jqote(TaskDisplay.tip, task)});
            //                    });
            //                });
            //            }
        });
        $('#tasksContainer').find('th[col]').append(stringFormat("<img class='Isort' src='{0}/Images/General/SortArrow.png'/>", baseUrl));
        this.load(0, this.loadCallback);
    },

    loadCallback: function (data)
    {
        $('#tasksContainer').clarizen_table('reload', data.list, data.count, data.hasMore);
    },

    load: function (page, callback)
    {
        this.loadCount = this.loadCount + 1 || 1;
        if (page === 0)
            $('#tasksContainer').clarizen_table('showLoading');

        // the first for google the second for conduit
        var state = $('#filterType .selected').add('#WorkItemState').attr('value');
        var role = $('#WorkItemFilter').val();
        var table = this;

        var curLoadCount = this.loadCount;
        var data = { q: $('#tbFilter').val() ? $('#tbFilter').val() : "", pageNumber: page, state: state, role: role };
        if (do_sort.state)
        {
            data.orderField = do_sort.state;
            data.ascending = do_sort.asc;
        }

        remoteRequest({
            url: baseUrl + '/tasks/list',
            contentType: "JSON",
            type: "POST",
            data: data,
            success: function (res)
            {
                if (curLoadCount == table.loadCount)
                {
                    if (res.ErrorMessage)
                        alert(res.ErrorMessage)
                    table.loading = false;
                    callback(res);
                }
                else
                    $('#tasksContainer').clarizen_table('enablePaging', res.hasMore);
            }
        });
    },

    resources:
    {
        added: [],
        deleted: [],
        updateTask: function ()
        {
            var taskID = $('.Info_Container [name="ID.Value"]').val();
            for (var i = 0; i < this.added.lenght; i++)
            {
                var el = this.added[i];
                var tasks = $('#tasksContainer').clarizen_table('getElements');
                var index = $.inObjectArray(tasks, function (el) { return el.ID.Value == taskID });
                if (index >= 0)
                {
                    var task = tasks[index];
                    task["Resources"] = task["Resources"] || [];
                    task["Resources"].push({ ID: { Value: el.id }, Name: el.name });
                }
            }
        }
    },

    loadControls: function ()
    {
        $('#btnSubmit').click(function () { update() });

        var handler = function (e, el)
        {
            var task = $('.Info_Container').data('task');


            if (!task.IndividualReporting)
                return true;

            openResourceEdit(task, $(this).attr('name').replace(/\..*/g, ""), el || $(this), function (task)
            {
                $('.Info_Container').data('task', task);
                TaskDisplay.displayDetails(task, true, ["PercentCompleted", "RemainingEffort", "ActualEffort"], true);
            });
            e.stopPropagation();

            return false;
        };

        $('.ddl-menu[name^="ActualEffort"], .ddl-menu[name^="RemainingEffort"]').ddl('setOption', "customClick", handler);

        $('[name="PercentCompleted"], [name^="ActualEffort"], [name^="RemainingEffort"]').click(handler);



        $('.autocomplete').each(function ()
        {
            var url = $(this).attr('url');
            var self = $(this);
            var loadFunc = function (q, callback)
            {
                remoteRequest({
                    url: url,
                    contentType: "JSON",
                    type: "POST",
                    data: { q: q },
                    success: callback
                });
            }

            $(this).tokenInput(loadFunc,
                {
                    theme: 'facebook',
                    rootClass: "FormInput",
                    preventDuplicates: true,
                    method: "POST",
                    width: 160,
                    onAdd: function (element)
                    {
                        var deleted = $.grep(TaskDisplay.resources.deleted, function (value)
                        {
                            return value != element;
                        });

                        if (deleted.length != TaskDisplay.resources.deleted.length)
                            TaskDisplay.resources.deleted.id = deleted.id;
                        else
                            TaskDisplay.resources.added.push(element);
                    },
                    onDelete: function (element)
                    {
                        var added = $.grep(TaskDisplay.resources.added, function (value)
                        {
                            return value.id != element.id;
                        });

                        if (added.length != TaskDisplay.resources.added.length)
                            TaskDisplay.resources.added = added;
                        else
                            TaskDisplay.resources.deleted.push(element);
                    } // ondelete
                }); // token input
        }); //$('.autocomplete').each


    }, //loadControls

    displayDetails: function (task, showEdit, changedColumns, highlight)
    {
        var form = $('.Info_Container');

        $('#task_tabs').tabs('select', 0);

        if (!changedColumns)
        {
            resetCustomFields();
            TaskDisplay.resources.added = [];
            TaskDisplay.resources.deleted = [];

            form.find('input, select, textarea').attr("for_saving", "false");
        }

        var that = this;
        var hasLoaded = false;
        $('#tasksPage').fadeOut(100, function ()
        {
            $('#tasksDetails').show();
            if (!hasLoaded)
            {
                $('#tasksDetails').show_loading(true);
            }
        });


        var callback = function (res)
        {
            hasLoaded = true;
            if (res.ErrorMessage)
            {
                alert(res.ErrorMessage);
                TaskDisplay.back();
                return;
            }
            $('#tasksDetails').show_loading(false);
            $("#tasksDetails").css("zoom", 0.1);
            $("#tasksDetails").css("zoom", 1);

            if (res.Data)
                res = res.Data;

            $('[name="ID.Value"]', form).val(res.ID.Value);
            form.data("task", res);
            for (var i = 0; i < displayColumns.length; i++)
            {
                if (changedColumns && $.inArray(displayColumns[i].Name, changedColumns) == -1)
                    continue;

                var prop = displayColumns[i];
                var val = res[prop.Name];
                var type = prop.Type || "Text";
                var formName = prop.Form || prop.Name;

                var formEl = $(stringFormat('[name="{0}"]', formName), ".Info_Container, .TaskHeader");
                var isDisabled = !res.Permissions[prop.origProperty || prop.Name];
                formEl.attr('disabled', isDisabled).ddl('disable', isDisabled).searchForm('disable', isDisabled);


                //                TODO: add support for not viewing data there are no view permissions for (server and client side). 
                //                debugger;
                //                if (res.Permissions[prop.origProperty || prop.Name] == null)
                //                    formEl.parent().parent().hide();
                //                else formEl.parent().parent().show();


                switch (type)
                {
                    case "Text":
                        if ($.type(val) === "number")
                            val = round(val, 2);
                        val = htmlUnEscape(val);

                        if (highlight && formEl.val() != val)
                            formEl.addClass('highlight');
                        formEl.val(val).data('notEscaped', true);

                        break;
                    case "Select":
                        formEl.val(val.Id.Value);
                        break;
                    case "SelectText":
                        formEl.html(stringFormat("<option value=''>{0}</option>", val));
                        break;
                    case "SelectObj":
                        formEl.html(stringFormat("<option value='{1}'>{0}</option>", val ? val.Values[0].Value : "", val ? val.Id.Value : ""));
                        break;
                    case "SelectID":
                        formEl.html(stringFormat("<option value='{1}'>{0}</option>", val ? val.Id.Value : "", val ? val.Id.Value : ""));
                        break;
                    case "Unit":
                        var textEl = $(stringFormat('.Info_Container [name="{0}.Value"]', formName));
                        var unitEl = $(stringFormat('.Info_Container [name="{0}.Unit"]', formName));

                        val.Value = round(val.Value, 0);

                        if (highlight)
                        {
                            if (textEl.val() != val.Value)
                                textEl.addClass('highlight');
                            if (unitEl[0].selectedIndex != val.Unit)
                                unitEl.addClass('highlight');
                        }

                        textEl.val(val.Value).attr('disabled', isDisabled);
                        unitEl.ddl('disable', isDisabled)[0].selectedIndex = val.Unit;
                        break;
                    case "Resource":
                        var el = $(stringFormat('[name="{0}"]', prop.Name));
                        el.tokenInput("clear");
                        for (var j = 0; val && j < val.length; j++)
                            el.tokenInput("add", { id: val[j].Resource.Id.Value, name: val[j].Resource.Values[0].Value, rid: val[j].ID.Value, editable: val[j].Delete });
                        break;
                }
            }
            $("select.FormInput").ddl('set');
            $('#statusImg').attr('src', stringFormat("{0}/Images/{1}", baseUrl, getStatusImage(res)));
            $('#parentName').html(res.Parent_Name == res.ParentProject_Name ? res.Parent_Name : res.ParentProject_Name + " > " + res.Parent_Name);
            $('#stateMenu').splitbutton("set", { item: $('#stateMenu').find("." + res.State.Id.Value.toLowerCase().replace(" ", "_")) });

            TaskDisplay.switchTaskDisplay(showEdit, true);
        };



        if (task)
            callback(task);
        else
        {
            task = $('#tasksContainer').clarizen_table('getSelectedElement');
            if (task.Loaded)
                callback(task);
            else
                remoteRequest({
                    url: baseUrl + "/tasks/details",
                    contentType: "JSON",
                    type: "POST",
                    data: { taskID: task.ID.Value },
                    success: function (res)
                    {
                        callback(res);
                    }
                });
        }
    },

    switchTaskDisplay: function (isEdit, refresh)
    {
        if (typeof (isEdit) != "undefined" && isEdit != null)
            TaskDisplay.IsEditMode = isEdit;
        else isEdit = TaskDisplay.IsEditMode;

        if (isEdit)
        {
            $(".FormInput").removeClass("Hide2");
            $(".FormDisplay").hide();
        }
        else
        {
            $(".FormInput").addClass("Hide2");

            // IE7 hack to hide selects
            $("a.PSelect").css("zoom", 0.1);
            $("a.PSelect").css("zoom", 1);

            if ($(".FormDisplay").length && !refresh)
                $(".FormDisplay").show();
            else
            {
                $(".FormDisplay").not('[type="button"]').remove();
                $(".FormDisplay").show();
                $(".FormInput").each(function ()
                {
                    var val;
                    if ($(this).is('[type="button"]'))
                    {
                        //                        if(this.id != 'btnCancel')
                        //                            $(this).after("<input type='button' class='FormDisplay' value='Edit' onclick='TaskDisplay.switchTaskDisplay(true);'/>");
                        //                        else
                        //                            $(this).after("<span type='button' class='FormDisplay Link' onclick='TaskDisplay.back();'>back</span>");
                        //                        return;
                    }
                    else if ($(this).is(':checkbox'))
                        val = $(this).attr('checked') ? "yes" : "no";
                    else if ($(this).is('input, textarea'))
                        val = $(this).val();
                    else if ($(this).is('.autocomplete'))
                    {
                        var values = $(this).tokenInput("getList");
                        val = $.map(values, function (el) { return el.name }).join(",");
                    }
                    else val = $(this).find(stringFormat('option[value="{0}"]', $(this).val())).html();
                    if (val)
                    {
                        if ($(this).data('notEscaped'))
                            val = htmlEscape(val);
                        $(this).after(stringFormat("<span class='FormDisplay' style='width:{1};display:inline-block'>{0}</span>", val, $(this).is('textarea') ? "99%" : $(this).width() + "px"));
                    }
                });
            }
        }
    }
};

var displayColumns = [
                {Name:"Name"},
                {Name:"Description"},
                {Name:"Parent_Name", Form:"ParentID", Type:"SelectText"},
                {Name:"PercentCompleted"},
                {Name:"StartDateString", Form: "StartDate", origProperty: "StartDate" , DisplayName: "Start Date", Class:"Date"},
                {Name:"DueDateString", Form: "DueDate", origProperty: "DueDate", DisplayName: "Due Date", Class:"Date"},
                {Name:"Duration", Type: "Unit"},
                {Name:"Work", Type: "Unit"},
                {Name:"ActualEffort", Type: "Unit"},
                {Name:"RemainingEffort", Type: "Unit"},
                {Name:"TrackStatus", Form:"TrackStatusID", Type: "Select"},
                {Name:"Importance", Form:"ImportanceID", Type: "Select"},
                {Name:"State", Form:"StateID", Type: "SelectID"},
                {Name:"Manager", Form:"ManagerID", Type: "SelectObj"},
                {Name:"TaskType", Form:"TaskTypeID", Type: "Select"},
                {Name:"Resources", Type: "Resource"}
            ];

        function do_sort(state, func)
        {
            if(do_sort.state == state)
                do_sort.asc = !do_sort.asc;
            else do_sort.state = state;
            TaskDisplay.load(0, TaskDisplay.loadCallback);
        }

        do_sort.state = 'Name';
        do_sort.asc = true;


        function update_note(type)
        {
            var data = $('.Edit_Pop input').serialize();
            var entityID = $('.Edit_Pop').attr('entity_id');
            data += "&ID.TypeName=" +  type;
            if(entityID)
                data += "&ID.Value=" +  entityID;
            else data += stringFormat("&AttachedTo.Id.Value={0}&AttachedTo.Id.TypeName={1}", $('.Info_Container [name="ID.Value"]').val() ,"Task");
            data += "&Comment=" + tinyMCE.activeEditor.save();
            remoteRequest({
                url: baseUrl + "/attachments/edit",
                contentType: "JSON",
                type: "POST",
                data: data,
                success: function (res)
                {
                    if (res && res.Data)
                    {
                        if(entityID)
                        {
                            alert("The record has been updated.")
                            var note = $(stringFormat('.Note[entity_id={0}]', entityID));
                            note.find('.Text').html(res.Data.Comment);
                            note.find('.VisibilityID').html(res.Data.VisibilityID);
                            $('.Edit_Pop').dialog('close');
                        }
                        else
                        {
                            alert("The record has been created.")
                            $(stringFormat('.{0}_Container', type)).jqoteapp("\
                                <div class='Note' entity_id='<%=this.ID.Value%>'>\
                                    <div class='Text'><%=this.Comment%></div>\
                                    <div class='Date'><%=this.CreatedBy_Name%> on <%=this.CreatedOnString%>\
                                        <span class='VisibilityID'><%=this.Visibility.Id%></span>\
                                        <span class='Link' action='edit'>Edit</span>\
                                        <span class='Link' action='delete'>Delete</span>\
                                    </div>\
                                    <div class='Comments'></div>\
                                </div>", res.Data);
                            var entity = $("[entity_id=" + res.Data.ID.Value + "]");

                            notes_loaded(entity);
                            $('.Edit_Pop').dialog('close');
                        }
                    }
                    else alert(res.ErrorMessage)
                }
            });
        };

        function deleteEntity(entityID, type)
        {
            remoteRequest({
                url: baseUrl + "/entities/delete",
                contentType: "JSON",
                type: "POST",
                data: {id: entityID, type:type},
                success: function (res)
                {
                    alert("Deleted!");
                    var e = $("[entity_id=" + entityID + "]");
                    e.fadeOut(function(){e.remove()});
                }
            });
        }

        function notes_loaded(container)
        {
            var editTmpl = "<div class='Edit_Pop' title='<%=this.title%>'>\
                                        <div class='Text'><textarea name='Comment' id='ta_editor'><%=this.Text%></textarea></div>\
                                        <div>\
                                            <input type='radio' <%=!this.Public? 'checked=\"checked\"': ''%> value='Private' name='VisibilityID' id='Visibility1'/><label for='Visibility1'>Private</label>\
                                            <input type='radio' <%=this.Public? 'checked=\"checked\"': ''%> value='Public' name='VisibilityID' id='Visibility2'/><label for='Visibility2'>Public</label>\
                                        </div>\
                                    </div>";
            $('.NewLink', container).click(function ()
            {
                var type = $(this).attr('type');
                $('.Edit_Pop').remove();
                var pop = $.jqote(editTmpl, {Text:"", Public:true, title: "New " + type});
                $(pop).dialog({
                        modal:true,
                        close: function(){$('.Edit_Pop').remove();},
                        buttons: [
                                    {
                                        text: "Save",
                                        click: function (){update_note(type);}
                                    },
                                    {
                                        text: "Cancel",
                                        click: function () { $(this).dialog("close"); }
                                    }
                                ]
                    });
                tinyMCE.init({
                        mode: "exact",
                        elements: "ta_editor"
                    });

                return false;
            });
            $('.Link', container || $(".Note_Container")).click(function ()
            {
                    var action = $(this).attr('action');
                    var type = $(this).closest("[e_type]").attr("e_type");
                    $('.Edit_Pop').remove();
                    var note = $(this).closest('.Note');
                    var entity_id = note.attr('entity_id');

                    switch($(this).attr('action'))
                    {
                        case "edit":
                            var pop = $.jqote(editTmpl, {Text:note.find('.Text').html(), Public:note.find('.VisibilityID').html() == "Public", title: "Edit Note"});
                            $(pop).dialog({
                                modal:true,
                                close: function(){$('.Edit_Pop').remove();},
                                buttons: [
                                            {
                                                text: "Update",
                                                click: function (){update_note(type);}
                                            },
                                            {
                                                text: "Cancel",
                                                click: function () { $(this).dialog("close"); }
                                            }
                                        ]
                            });
                            $('.Edit_Pop').attr('entity_id', entity_id);
                            tinyMCE.init({
                                mode: "exact",
                                elements: "ta_editor"
                            });
                            break;
                        case "delete":
                            deleteEntity(entity_id, type);
                            break;
                   }

                    
            });
        }

        function resetCustomFields()
        {
            var label = $('.CustomContainer .Label');
            $('#CustomFields').html('');
            getCustomFields.fields = null;
            label.html(label.html().replace("-", "+"));
        }

        function getCustomFields() 
        {
            if ($('.customField').length != 0)
            {
                resetCustomFields()
                return;
            }
            
            var label = $('.CustomContainer .Label');
            label.html(label.html().replace("+", "-"));

            var renderFields = function (values)
            {
                getCustomFields.fields = values;
                var row;
                for (var i = 0; i < values.length; i++)
                {
                    if (i % 4 == 0)
                    {
                        row = $('<div class="Row">');
                        $("#CustomFields").append(row);
                    }

                    var fieldName = stringFormat("CustomFields[{0}]", i);
                    var inputs = new window["T_" + values[i].TypeName]().getControls(values[i].Name, fieldName, htmlUnEscape(values[i].Value), "FormInput", null, values[i].R_Type);

                    var prop = $("<div class='Property'>");
                    row.append(prop);

                    prop.append(stringFormat("<div class='customField' id='cf{1}'>\
                            <div class='Label'>{0}</div>\
                        </div>", [values[i].Label, i]));

                    prop.find('.customField').append(inputs);
                    prop.find('.customField').find('input, select').data('notEscaped', true);
                }
                AttachEvents($("#CustomFields"));
                for (var i = 0; i < values.length; i++)
                {
                    var isDisabled = values[i].Disabled;
                    $("#cf" + i).find('input, select, a').attr('disabled', isDisabled)
                                                                    .ddl('disable', isDisabled).searchForm('disable', isDisabled);
                }
                

                TaskDisplay.switchTaskDisplay(null, true);
            };

            if (getCustomFields.fields)
                renderFields(getCustomFields.fields);
            else
            {
                $("#CustomFields").css({height:70}).show_loading(true);
                getCustomFields.count = getCustomFields.count? getCustomFields.count + 1: 1;
                var count = getCustomFields.count;
                remoteRequest({
                    url: baseUrl + '/tasks/customFields',
                    contentType: "JSON",
                    type: "POST",
                    data: { id: $('.Info_Container [name="ID.Value"]').val() },
                    success: function (data) {
                        if (getCustomFields.count == count) {
                            $("#CustomFields").css("height", "").show_loading(false);
                            renderFields(data);

                        }
                    }
                });
            }
        }

        function openNotes()
        {
            remoteRequest({
                url: baseUrl + '/attachments/index',
                contentType: "text/html",
                type: "GET",
                data: { id: $('.Info_Container [name="ID.Value"]').val(), type: "Note" },
                success: function (res)
                {
                    try
                    {
                        $(res).dialog({
                            close: function(){$(this).remove();},
                            width:340,
                            modal:true,
                            buttons: [{
                                            text: "Close",
                                            click: function () { $(this).dialog("close"); }
                                        }]
                        });
                    }catch(er){}
                    $('#att_tabs').tabs({cache: true,load:function(e,ui){notes_loaded(ui.panel)}});
                    notes_loaded();
                }
            });
        }

        function getStatusImage(task)
        {
            var status = task.TrackStatus && task.TrackStatus.Id ? task.TrackStatus.Id.Value : "";
            switch (status.toLowerCase())
            {
                case "not active":
                    return "iconNotActive.jpg";
                    break;
                case "at risk":
                    return "iconAtRisk.jpg";
                    break;
                case "off track":
                    return "iconOffTrack.jpg";
                    break;
                case "on track":
                default:
                    return "iconOnTrack.jpg";
                    break;
            }
        }


        function getImportanceImage(task)
        {
            var importance = task.Importance && task.Importance.Id ? task.Importance.Id.Value : "";
            switch (importance)
            {
                case "Critical":
                case "High":
                    return stringFormat("<img src='{1}/Images/Importance_{0}.gif'/>", importance, baseUrl);
                default:
                    return "";
                    break;
            }
        }

        

        function AttachEvents(container)
        {
            $(".Date", container).datepicker(
            {
                dateFormat: 'yy-mm-dd'
            });

            $('.Numeric', container).blur(function (event)
            {
                if (!/^(\d+(\.\d+)?)?$/.test($(this).val()))
                    $(this).val(0);
            });

            $('.EntitySearch', container).each(function()
            {
                var type = $(this).attr('type_name');
                var filter = type == "User"? "userFilter": "";
                $(this).searchForm({ type: type, baseUrl: baseUrl, filter: filter, className:"FormInput", pName: $(this).closest(".Property").find(".Label").text() });
            });
        
            $('input, select, textarea', container).change(function()
            {   
                $(this).closest('.Property, .Property2').find('input, select, textarea').attr("for_saving", "true")
            });
            $('.ddl-menu', container).addClass('Hide1').ddl({className:"FormInput"});
            $('.Documents_Container select', container).ddl();

            var ddls = $('a.PSelect');
            ddls.each(function (idx, el) { $(el).css('z-index', ddls.length - idx); });
        }

        function SetState(type, callback)
        {
            remoteRequest({
                url: baseUrl + '/tasks/SetState',
                contentType: "JSON",
                type: "POST",
                data: { taskID: $('.Info_Container [name="ID.Value"]').val(), state: type },
                success: function (res)
                {
                    if (res && res.Data)
                    {
                        alert("The record has been updated.")
                        callback(false);
                    }
                    else
                    {
                        alert(res.ErrorMessage)
                        callback(true);
                    }
                }
            });
        }



        var initPage = function () {
            AttachEvents();
            $('#OriginatedFromID').focus(function () {
                var table = new ProjectTable().show(baseUrl, true, function (val) {
                    $('#OriginatedFromID').html(stringFormat("<option value='{0}'>{1}</option>", val.id, val.name))
                });
                table.select($(this).val());
            });


            $('#AssignedTo').searchForm({ type: "User", baseUrl: baseUrl, filter: "userFilter", className: "FormInput", pName: "Manager" });

            $('#stateMenu').splitbutton({
                preclick: function (item, func) {
                    $('#stateMenu').closest(".Property").show_loading(true, { "background-color": "#CADCE7" });
                    SetState(item.id, function (fail) {
                        func(fail);
                        $('#stateMenu').closest(".Property").show_loading(false);
                    });
                },
                menu: '#mm',
                withIcon: true
            });

            $('#AdditionalFieldsLink').click(function () {
                $('.AdditionalFields').toggle();
                
            });

            window.setTimeout(function () {
                if (getCustomFields)
                    $('.CustomContainer .Label').click(getCustomFields);
                else window.setTimeout(arguments.callee, 500);
            }, 500);


            TaskDisplay.init();

            $('#tbFilter').keyup(function () {
                var tb = $(this);
                var timer = $('#tbFilter').data('timer');
                if (timer)
                    window.clearTimeout(timer);

                if ($('#tbFilter').data('last') == $('#tbFilter').val())
                    return;

                timer = window.setTimeout(function () {
                    $('#tbFilter').data('last', $('#tbFilter').val());
                    TaskDisplay.load(0, TaskDisplay.loadCallback);
                }, 400);
                $('#tbFilter').data('timer', timer);
            });

            $('.filter').change(function () {
                TaskDisplay.load(0, TaskDisplay.loadCallback);
            });

            $('#filterType .option').click(function () {
                $('#filterType .option').removeClass('selected');
                $(this).addClass('selected');
                TaskDisplay.load(0, TaskDisplay.loadCallback);
            });

            $('#WorkItemState').ddl({ maxTextWidth: 120 });
            $('#WorkItemFilter').ddl({ maxTextWidth: 180, extraWidth: 120, DDWidth: 300 });
            var lastLoadedTask = 0;
            $('#task_tabs').tabs({
                select: function (event, ui) {
                    var taskID = $('.Info_Container [name="ID.Value"]').val();
                    if (ui.index == 1 && lastLoadedTask != taskID) {
                        lastLoadedTask = taskID;
                        $('.DocumentList .Document').remove();
                        $('.DocumentList').show_loading(true);

                        remoteRequest({
                            url: baseUrl + '/Documents/_List',
                            contentType: "text/html",
                            type: "POST",
                            data: { taskID: taskID },
                            success: function (res) {
                                $('.DocumentList').show_loading(false);
                                if (res) {
                                    $(ui.panel).append(res);
                                    $('#TaskID', ui.panel).val(taskID);
                                }
                                else {
                                    alert(res.ErrorMessage)
                                    callback(true);
                                }
                            }
                        });
                    }
                }
            }); //$('.Info_Container [name="ID.Value"]').val()
        };

        initPage();

